import React, { useState, useEffect } from 'react';
import Icon from 'react-native-vector-icons/FontAwesome';
import { View, Text, StyleSheet, TextInput, ScrollView, Image, TouchableOpacity, ActivityIndicator } from 'react-native';
import { getBooks, getHotBooks } from '../src/services/bookService';
import AsyncStorage from '@react-native-async-storage/async-storage';

const HomeMain = ({ navigation }) => {
    const [recommendBooks, setRecommendBooks] = useState([]);
    const [hotList, setHotList] = useState([]);
    const [loading, setLoading] = useState(true);
    const [searchQuery, setSearchQuery] = useState('');
    const [error, setError] = useState(null);

    const formatDate = (dateString) => {
        const date = new Date(dateString);
        return `${date.getFullYear()}年${(date.getMonth() + 1).toString().padStart(2, '0')}月${date.getDate().toString().padStart(2, '0')}日`;
    };

    useEffect(() => {
        fetchData();
    }, []);

    const fetchData = async () => {
        try {
            setLoading(true);
            setError(null);
            const [booksData, hotBooksData] = await Promise.all([
                getBooks(),
                getHotBooks(),
            ]);

            if (Array.isArray(booksData)) {
                // 随机选择5本书作为推荐
                const shuffled = [...booksData].sort(() => 0.5 - Math.random());
                setRecommendBooks(shuffled.slice(0, 5));
            }

            if (Array.isArray(hotBooksData)) {
                setHotList(hotBooksData);
            }
        } catch (error) {
            console.error('Error fetching data:', error);
            setError(error.message);
        } finally {
            setLoading(false);
        }
    };

    const handleSearch = () => {
        if (searchQuery.trim()) {
            navigation.navigate('Search', { keyword: searchQuery.trim() });
            setSearchQuery(''); // 清空搜索框
        }
    };

    if (loading) {
        return (
            <View style={styles.loadingContainer}>
                <ActivityIndicator size="large" color="#70a1ff" />
            </View>
        );
    }

    return (
        <ScrollView style={styles.container}>
            {error && (
                <View style={styles.errorContainer}>
                    <Text style={styles.errorText}>{error}</Text>
                </View>
            )}

            <View style={styles.searchContainer}>
                <TouchableOpacity onPress={handleSearch} style={styles.searchIcon}>
                    <Icon name="search" size={20} color="#999" />
                </TouchableOpacity>
                <TextInput
                    placeholder="搜索书籍"
                    style={styles.searchInput}
                    placeholderTextColor="#999"
                    value={searchQuery}
                    onChangeText={setSearchQuery}
                    onSubmitEditing={handleSearch}
                    returnKeyType="search"
                />
                {searchQuery ? (
                    <TouchableOpacity onPress={() => setSearchQuery('')} style={styles.clearIcon}>
                        <Icon name="times-circle" size={18} color="#999" />
                    </TouchableOpacity>
                ) : null}
            </View>

            <View style={styles.rcmCard}>
                <Text style={styles.rcmTitle}>推荐书籍</Text>
                <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                    {recommendBooks.map((book, index) => (
                        <TouchableOpacity
                            key={book.id}
                            style={styles.rcmItem}
                            onPress={() => navigation.navigate('Home', { screen: 'BookContent', params: { bookId: book.id } })}
                        >
                            <Image
                                source={{ uri: book.image || 'https://via.placeholder.com/150x200/e0e0e0/757575?text=Book' }}
                                style={styles.rcmCover}
                            />
                            <View style={styles.bookInfoContainer}>
                                <Text style={styles.rcmBookTitle}>{book.title}</Text>
                                <View style={styles.statusRow}>
                                    <Text style={styles.rcmBookStatus}>{book.status}</Text>
                                    <Text style={styles.rcmBookAuthor}>{book.author}</Text>
                                </View>
                                <Text style={styles.rcmBookIntro} numberOfLines={2}>
                                    {book.description || '暂无简介'}
                                </Text>
                            </View>
                        </TouchableOpacity>
                    ))}
                </ScrollView>
            </View>

            <View style={styles.hotListCard}>
                <View style={styles.hotListHeader}>
                    <Text style={styles.hotListTitle}>热门榜单</Text>
                    <TouchableOpacity onPress={fetchData}>
                        <Icon name="refresh" size={20} color="#666" />
                    </TouchableOpacity>
                </View>
                {hotList.map((book, index) => (
                    <TouchableOpacity
                        key={book.id}
                        style={styles.hotItem}
                        onPress={() => navigation.navigate('Home', { screen: 'BookContent', params: { bookId: book.id } })}
                    >
                        <Text style={[
                            styles.rankNum,
                            index < 3 && styles.topRank
                        ]}>{index + 1}</Text>
                        <Image
                            source={{ uri: book.image || 'https://via.placeholder.com/150x200/e0e0e0/757575?text=Book' }}
                            style={styles.hotCover}
                        />
                        <View style={styles.hotInfo}>
                            <Text style={styles.hotTitle} numberOfLines={1}>{book.title}</Text>
                            <Text style={styles.hotAuthor} numberOfLines={1}>
                                {book.author} · {book.category} · {book.status}
                            </Text>
                            <Text style={styles.updateTime}>
                                {formatDate(book.update_time)}
                            </Text>
                        </View>
                        <View style={styles.commentContainer}>
                            <Text style={styles.commentCount}>{book.comment_count}</Text>
                            <Text style={styles.commentLabel}>评论</Text>
                        </View>
                    </TouchableOpacity>
                ))}
            </View>
        </ScrollView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    searchContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#fff',
        borderRadius: 20,
        paddingHorizontal: 15,
        height: 40,
        margin: 15,
        elevation: 2,
    },
    searchIcon: {
        marginRight: 10,
        padding: 5,
    },
    searchInput: {
        flex: 1,
        height: '100%',
        fontSize: 14,
        color: '#333',
        padding: 0,
    },
    clearIcon: {
        marginLeft: 10,
        padding: 5,
    },
    rcmCard: {
        backgroundColor: '#fff',
        padding: 15,
        marginBottom: 15,
    },
    rcmTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        marginBottom: 15,
        color: '#333',
    },
    rcmItem: {
        flexDirection: 'row',
        width: 300,
        marginRight: 15,
        backgroundColor: '#f9f9f9',
        borderRadius: 8,
        padding: 10,
    },
    rcmCover: {
        width: 100,
        height: 140,
        borderRadius: 4,
    },
    bookInfoContainer: {
        flex: 1,
        marginLeft: 10,
        justifyContent: 'center',
    },
    rcmBookTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 5,
    },
    rcmBookScore: {
        color: '#ff4757',
        fontSize: 16,
        fontWeight: 'bold',
        marginBottom: 8,
    },
    statusRow: {
        flexDirection: 'row',
        marginBottom: 8,
    },
    rcmBookStatus: {
        fontSize: 12,
        color: '#70a1ff',
        backgroundColor: '#e6f2ff',
        paddingHorizontal: 6,
        paddingVertical: 2,
        borderRadius: 3,
        marginRight: 10,
    },
    rcmBookWords: {
        fontSize: 12,
        color: '#666',
    },
    rcmBookAuthor: {
        fontSize: 12,
        color: '#666',
        marginLeft: 10,
    },
    rcmBookIntro: {
        fontSize: 12,
        color: '#666',
        lineHeight: 18,
        marginTop: 5,
    },
    hotListCard: {
        backgroundColor: '#fff',
        padding: 15,
        marginBottom: 15,
    },
    hotListHeader: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: 15,
    },
    hotListTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#333',
    },
    hotItem: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 15,
        paddingVertical: 10,
        borderBottomWidth: 1,
        borderBottomColor: '#f0f0f0',
    },
    rankNum: {
        width: 24,
        textAlign: 'center',
        fontSize: 16,
        fontWeight: 'bold',
        color: '#999',
    },
    topRank: {
        color: '#ff4757',
    },
    hotCover: {
        width: 50,
        height: 70,
        borderRadius: 4,
        marginLeft: 10,
        marginRight: 15,
    },
    hotInfo: {
        flex: 1,
    },
    hotTitle: {
        fontSize: 16,
        fontWeight: '500',
        color: '#333',
        marginBottom: 5,
    },
    hotAuthor: {
        fontSize: 12,
        color: '#666',
        marginBottom: 3,
    },
    updateTime: {
        fontSize: 12,
        color: '#999',
    },
    commentContainer: {
        alignItems: 'center',
        minWidth: 50,
    },
    commentCount: {
        color: '#70a1ff',
        fontSize: 16,
        fontWeight: 'bold',
    },
    commentLabel: {
        fontSize: 12,
        color: '#999',
    },
    loadingContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    errorContainer: {
        padding: 15,
        backgroundColor: '#ffe6e6',
        marginHorizontal: 15,
        marginTop: 15,
        borderRadius: 8,
    },
    errorText: {
        color: '#ff4d4d',
        fontSize: 14,
    },
});

export default HomeMain;